<template>
	<div class="sample-editor">
		<div class="sample-editor-header">
			<div class="sample-editor-header-title">源代码编辑器</div>
			<div class="sample-editor-header-right">
				<div class="sample-editor-header-right-box" @click="play">
					<el-icon :size="12">
						<VideoPlay />
					</el-icon>
					运行
				</div>
				<div class="sample-editor-header-right-box" @click="refresh">
					<el-icon :size="12">
						<Refresh />
					</el-icon>
					重置
				</div>
				<div class="sample-editor-header-right-box" @click="onCopy">
					<el-icon :size="12">
						<CopyDocument />
					</el-icon>
					复制
				</div>
			</div>
		</div>
		<!-- 代码编辑器 -->
		<div ref="editorContainer" class="sample-editor-code"></div>
	</div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus'
import { copyText } from 'vue3-clipboard'
import * as monaco from 'monaco-editor';

const editorContainer = ref(null);
const content = ref(null)
let editorInstance = null;
const props = defineProps({
	code: {
		type: String,
		required: true
	},
})

watch(
	() => props.code,
	(newValue) => {
		content.value = newValue
		if (editorInstance) {
			editorInstance.dispose();
		}
		initCodeContainer();
		if (editorInstance) {
			editorInstance.setValue(newValue);
		}
	}
)

const emit = defineEmits(['codeChange'])

const initCodeContainer = async () => {
	editorInstance = monaco.editor.create(editorContainer.value, {
		value: props.code,
		minimap: { enabled: false },
		language: 'html',
		theme: 'vs-dark',
		automaticLayout: true,
		wordWrap: 'on'
	});
}

const play = () => {
	content.value = editorInstance.getValue();
	emit('codeChange', content.value);
}

const refresh = () => {
	editorInstance.setValue(props.code);
	emit('codeChange', props.code);
}

const onCopy = () => {
	copyText(content.value, undefined, (error) => {
		if (error) {
			ElMessage.warning(`复制失败: ${error} ！`);
		} else {
			ElMessage.success('内容已复制到剪切板！');
		}
	})
}
</script>

<style lang="scss" scoped>
.sample-editor {
	height: 100%;
	background-color: #24272d;
	color: #fff;
	position: relative;

	.sample-editor-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 38px;
		padding: 0 1em;
		font-size: 14px;
		background-color: #24272d;
		position: sticky;
		top: 0;
		z-index: 10;
		border-bottom: 1px solid #333;

		&-right {
			display: flex;
			gap: 16px; // 增加按钮间距

			&-box {
				cursor: pointer;
				color: var(--el-color-primary) !important;
				display: flex;
				align-items: center;
				gap: 4px;
				padding: 4px 8px;
				border-radius: 3px;
				transition: all 0.2s;

				&:hover {
					background-color: rgba(69, 163, 255, 0.1);
				}

				.el-icon {
					margin-right: 4px;
				}
			}
		}
	}

	.sample-editor-code {
		display: block !important;
		height: calc(100vh - 38px);
		width: 100%;
		overflow-y: scroll;

		&::-webkit-scrollbar {
			display: none;
		}
	}
}
</style>
